package com.sita.cfmoto.ui.fragments;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.sita.cfmoto.R;
import com.sita.cfmoto.event.HasBindVehicleEvent;
import com.sita.cfmoto.my.activity.MyVehicleActivity;
import com.sita.cfmoto.rest.model.BindedVehicle;
import com.sita.cfmoto.rest.model.VehicleData;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.ui.activity.DeviceStatusActivity;
import com.sita.cfmoto.ui.activity.GeofenceSettingActivity;
import com.sita.cfmoto.ui.activity.MapActivity;
import com.sita.cfmoto.ui.view.RotateMenuView;
import com.sita.cfmoto.utils.VehicleUtils;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

public class HomeFragment extends Fragment {

    private final String TAG = HomeFragment.class.getSimpleName();
    private final int POWER_LIFE = 98;
    private final int TOTAL_LONG = 90;
    private final int DEFAULT_POWER_LOST = 30;
    @Bind(R.id.vehicle_mode_value)
    TextView vehicleMode;
    @Bind(R.id.main_rotate_menu)
    RotateMenuView mMenuView;
    @Bind(R.id.location_value_txt)
    TextView locationValue;
    @Bind(R.id.power_value_txt)
    TextView powerValue;
    @Bind(R.id.mileage_value_txt)
    TextView mileageValue;
    @Bind(R.id.temperature_value_txt)
    TextView temperatureValue;
    @Bind(R.id.pro_oil)
    ProgressBar oilProgress;
    @Bind(R.id.pro_mileage)
    ProgressBar mileageProgress;
    @Bind(R.id.pro_temperature)
    ProgressBar temperatureProgress;
    @Bind(R.id.image_vehicle)
    ImageView vehicleImg;
    private GeocodeSearch geocodeSearch;
    private Drawable redProgress, redProgress01, redProgress02, blueProgress, blueProgress01, blueProgress02, grayProgress;
    private Handler mHandler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            fetchVehicleData();
            mHandler.postDelayed(this, 15000);
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, null);
        ButterKnife.bind(this, view);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initMenu();
        initProgress();
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onPause() {
        super.onPause();
        stopTimer();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private void initProgress() {
        oilProgress.setIndeterminate(false);
        mileageProgress.setIndeterminate(false);
        temperatureProgress.setIndeterminate(false);
        redProgress = GlobalContext.getGlobalContext().getResources().getDrawable(R.drawable.bg_pro_red);
        blueProgress = GlobalContext.getGlobalContext().getResources().getDrawable(R.drawable.bg_pro_blue);
        redProgress01 = GlobalContext.getGlobalContext().getResources().getDrawable(R.drawable.bg_pro_red_1);
        blueProgress01 = GlobalContext.getGlobalContext().getResources().getDrawable(R.drawable.bg_pro_blue_1);
        redProgress02 = GlobalContext.getGlobalContext().getResources().getDrawable(R.drawable.bg_pro_red_2);
        blueProgress02 = GlobalContext.getGlobalContext().getResources().getDrawable(R.drawable.bg_pro_blue_2);
        grayProgress = GlobalContext.getGlobalContext().getResources().getDrawable(R.drawable.pro_gray);
    }

    private void initMenu() {
        mMenuView.registerMenuListener(new RotateMenuView.OnMenuSelectedListener() {
            @Override
            public void onSelected(RotateMenuView.MENU_ITEM item) {
                switch (item) {
                    case ITEM_1:
                        clickItem1();
                        break;
                    case ITEM_2:
                        clickItem2();
                        break;
                    case ITEM_3:
                        clickItem3();
                        break;
                    case ITEM_4:
                        clickItem4();
                        break;
                    case MENU_CLOSED:
//                        onMenuClosed();
                        break;
                    case MENU_OPEN:
//                        onMenuOpen();
                        break;
                    default:
                        break;
                }
            }
        });
    }


    private void clickItem1() {
        startActivity(GeofenceSettingActivity.newIntent());
    }

    private void clickItem2() {
        startActivity(new Intent(getActivity(), MyVehicleActivity.class));
    }

    private void clickItem3() {
        startActivity(DeviceStatusActivity.newIntent());
    }

    private void clickItem4() {
        startActivity(new Intent(getActivity(), MapActivity.class));
    }


    @OnClick({R.id.location_icon, R.id.location_item, R.id.location_value_txt})
    void clickLocation() {
        startActivity(new Intent(getActivity(), MapActivity.class));
    }

    private void fetchVehicleData() {
        VehicleUtils.FetchVehicleData(new VehicleUtils.FetchVehicleDataCallback() {
            @Override
            public void onVehicleDataFetched(VehicleData vehicleData) {
                if (vehicleData != null) {
                    long oilData = vehicleData.oilMass;
                    long mileageData = vehicleData.leftDistance;
                    long temperatureData = vehicleData.waterTemperature;
                    powerValue.setText(GlobalContext.getGlobalContext().getString(R.string.power_value, oilData));
                    mileageValue.setText(GlobalContext.getGlobalContext().getString(R.string.mileage_value, mileageData));
                    temperatureValue.setText(GlobalContext.getGlobalContext().getString(R.string.temperature_value, temperatureData));
                    oilProgress.setProgress((int) oilData);
                    mileageProgress.setProgress((int) mileageData);
                    temperatureProgress.setProgress((int) temperatureData);
                    if (oilData < 20) {
                        oilProgress.setProgressDrawable(redProgress);
                    } else {
                        oilProgress.setProgressDrawable(blueProgress);
                    }
                    if (mileageData < 20) {
                        mileageProgress.setProgressDrawable(redProgress01);
                    } else {
                        mileageProgress.setProgressDrawable(blueProgress01);
                    }
                    if (temperatureData > 70) {
                        temperatureProgress.setProgressDrawable(redProgress02);
                    } else {
                        temperatureProgress.setProgressDrawable(blueProgress02);
                    }

                    double lat = vehicleData.lat;
                    double lng = vehicleData.lng;
                    LatLng latLng = new LatLng(lat, lng);
                    VehicleUtils.updateLocation(latLng);
                    LatLonPoint latLonPoint = new LatLonPoint(lat, lng);
                    reGeocodeVehicleAddress(latLonPoint);
                } else {
                    powerValue.setText(GlobalContext.getGlobalContext().getString(R.string.power_value, 0));
                    mileageValue.setText(GlobalContext.getGlobalContext().getString(R.string.mileage_value, 0));
                    temperatureValue.setText(GlobalContext.getGlobalContext().getString(R.string.temperature_value, 0));
                }
            }
        });
    }

    private void reGeocodeVehicleAddress(LatLonPoint latLonPoint) {
        geocodeSearch = new GeocodeSearch(getActivity());
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                //解析result获取逆地理编码结果
                RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();
                locationValue.setText(regeocodeAddress.getProvince()+regeocodeAddress.getCity()+regeocodeAddress.getDistrict()+"...");
            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

            }
        });
        //latLonPoint参数表示一个Latlng，第二参数表示范围多少米，GeocodeSearch.AMAP表示是国测局坐标系还是GPS原生坐标系
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);
        geocodeSearch.getFromLocationAsyn(query);
    }

    private void startTimer() {
        mHandler.post(runnable);
    }

    private void stopTimer() {
        mHandler.removeCallbacks(runnable);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden) {
            stopTimer();
        } else {
//            if (LocalStorage.hasBindVehicle()) {
            startTimer();
//            }
        }
    }

    public void onEventMainThread(HasBindVehicleEvent event) {
        if (event.hasBindVehicle) {
            startTimer();
           BindedVehicle bindedVehicle = VehicleUtils.getCurrentSelectedVehicle();
            vehicleMode.setText(bindedVehicle.machineType);
            vehicleImg.setImageResource(R.mipmap.vehicle_cfmoto_nk150);
        } else {
            stopTimer();
            vehicleMode.setText("--");
            vehicleImg.setImageResource(R.drawable.no_vehicle);
            locationValue.setText("无");
            powerValue.setText("--");
            mileageValue.setText("--");
            temperatureValue.setText("--");
            oilProgress.setProgressDrawable(grayProgress);
            mileageProgress.setProgressDrawable(grayProgress);
            temperatureProgress.setProgressDrawable(grayProgress);
        }
    }
}
